﻿using BLL;
using DAL;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MDMUI.SingleBatch
{
    public partial class SingleBatchOutbound : Form
    {
        private SingleBatchEntryBLL singleBatchEntryBLL = new SingleBatchEntryBLL();
        public SingleBatchOutbound()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (int.TryParse(textBox1.Text, out int batchId))
            {
                // 调用 BLL 层的方法获取批次数据
                Batch batchData = singleBatchEntryBLL.showBatchMeg(batchId);
                if (batchData == null)
                {
                    MessageBox.Show("未找到批次数据");
                    return;
                }

                // 检查产品的进出站状态
                Product productData = singleBatchEntryBLL.GetProductById(batchData.ProductId);
                if (productData.EntryAndExitStatus != "已进站")
                {
                    MessageBox.Show("产品未进站，请先进行进站");
                    return;
                }

                int totalProcessId = batchData.TotalProcessId;
                TotalProcess totalProcessData = singleBatchEntryBLL.GetTotalProcessById(totalProcessId);
                int stationId = totalProcessData.TotalProcessId;
                Station stationData = singleBatchEntryBLL.GetStationById(stationId);
                int productFlowId = productData.FlowId;
                int productStationId = productData.StationId;
                ProcessFlow FlowData = singleBatchEntryBLL.GetProcessFlowById(productFlowId);
                Station StationData = singleBatchEntryBLL.GetStationById(productStationId);

                // 将数据分配给窗体上的控件
                batchType.Text = batchData.BatchType;
                verboseType.Text = "Production";
                quantity.Text = batchData.Quantity.ToString();
                subQuantity.Text = batchData.SubQuantity.ToString();
                unit.Text = batchData.Unit.ToString();
                lockingState.Text = "未锁定";
                productNum.Text = batchData.ProductId.ToString();
                workOrderNum.Text = batchData.WorkOrderId.ToString();
                goodNum.Text = batchData.GoodQuantity.ToString();
                noGoodNum.Text = batchData.NGQuantity.ToString();
                wipStatus.Text = batchData.LockStatus.ToString();
                repairStatus.Text = "NotOnhold";
                processFlow.Text = FlowData.FlowName;
                versionNum.Text = FlowData.ProcessFlowVersion;
                describe.Text = FlowData.Description;
                scrapQty.Text = "0";
                scrapSubQty.Text = "0";
                processStatus.Text = "Wait";
                reworkStatus.Text = "unRework";
                station.Text = StationData.StationName;
                stationVesion.Text = StationData.StationVersion;
                StationDescription.Text = StationData.StationDescription;
            }
            else
            {
                MessageBox.Show("请输入有效的批次数");
            }
        }

        private void SingleBatchOutbound_Load(object sender, EventArgs e)
        {
            //设备表
            EquipmentRepository equipmentRepository = new EquipmentRepository();
            List<Equipment> equipmentData = equipmentRepository.GetAllEquipments();
            try
            {
                // 清空 ComboBox
                equipmentModel.Items.Clear();

                // 遍历设备数据并添加到 ComboBox
                foreach (var equipment in equipmentData)
                {
                    equipmentModel.Items.Add(equipment.EquipmentType);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error loading equipment models: {ex.Message}");
            }
            //获取工艺包表
            ProcessPackageRepository processPackageRepository = new ProcessPackageRepository();
            List<ProcessPackage> processPackageData = processPackageRepository.GetAllProcessPackages();
            try
            {
                // 清空 ComboBox
                package.Items.Clear();

                // 遍历设备数据并添加到 ComboBox
                foreach (var processPackage in processPackageData)
                {
                    package.Items.Add(processPackage.Name);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error loading equipment models: {ex.Message}");
            }
        }

        private void equipmentModel_SelectedIndexChanged(object sender, EventArgs e)
        {
            //设备表
            EquipmentRepository equipmentRepository = new EquipmentRepository();
            //设备下拉选项
            string selectedEquipmentModel = equipmentModel.SelectedItem?.ToString();
            int equipmentID = singleBatchEntryBLL.GetEquipmentIdByModel(selectedEquipmentModel);
            //int processCapacity = singleBatchEntryBLL.GetProcessCapacityByEquipmentModel(selectedEquipmentModel);
            //程序包下拉选项
            string selectedPackage = package.SelectedItem?.ToString();
            int processPackageId = singleBatchEntryBLL.GetProcessPackageIdByName(selectedPackage);
            //根据程序包id查找程序包数据
            ProcessPackage processPackageData = singleBatchEntryBLL.GetProcessPackageById(processPackageId);
            //获取工艺包表
            //ProcessPackageRepository processPackageRepository = new ProcessPackageRepository();
            //List<ProcessPackage> processPackageData = processPackageRepository.GetAllProcessPackages();
            //总工艺流程表
            Equipment equipmentData = singleBatchEntryBLL.GetEquipmentById(equipmentID);
            //设备说明
            equipmentDescription.Text = equipmentData.EquipmentDescription;
            //设备产品编号
            equipmentProductNum.Text = equipmentData.EquipmentModel;
            //状态
            deviceStatus.Text = equipmentData.EquipmentStatus;
            //锁定状态
            LockStatus.Text = equipmentData.LockStatus;
            //设备类型
            deviceType.Text = "Process";
            //详细类型
            DetailedEquipmentType.Text = equipmentData.DetailedEquipmentType;
            //载具
            status.Text = equipmentData.Status;
            //通信状态
            CommunicationStatus.Text = equipmentData.CommunicationStatus;
            //设备号
            equipemtNum.Text = equipmentData.EquipmentId.ToString();
        }

        private void package_SelectedIndexChanged(object sender, EventArgs e)
        {
            //程序包下拉选项
            string selectedPackage = package.SelectedItem?.ToString();
            int processPackageId = singleBatchEntryBLL.GetProcessPackageIdByName(selectedPackage);
            //根据程序包id查找程序包数据
            ProcessPackage processPackageData = singleBatchEntryBLL.GetProcessPackageById(processPackageId);
            //子程序名
            subProgramName.Text = processPackageData.Description;
            //设备程序名
            packageName.Text = processPackageData.Name;
            //批次程序名
            batchPackageName.Text = processPackageData.Name;
        }
        //修改产品表进出站状态，StationStepNumber+1，根据根据工站表的StationStepNumber来更新工站id和g工艺流程id
        private void button4_Click(object sender, EventArgs e)
        {

            try
            {
                // 获取产品ID
                string productNumText = productNum.Text.Trim();
                if (!int.TryParse(productNumText, out int productId)) // 在这里声明 productId
                {
                    MessageBox.Show("请输入有效的数字产品ID");
                    return;
                }

                // 检查产品的进出站状态是否为 “已进站”
                Product currentProductState = singleBatchEntryBLL.GetProductById(productId);
                if (currentProductState.EntryAndExitStatus != "已进站")
                {
                    MessageBox.Show("产品尚未进站，无法进行出站操作！");
                    return;
                }

                // 更新产品的进出站状态
                int updateResult = singleBatchEntryBLL.UpdateProductEntryAndExitStatus(productId, "未进站");

                if (updateResult > 0)
                {
                    MessageBox.Show("产品进出站状态更新成功！");
                    // 根据根据工站表的StationStepNumber来更新工站id和工艺流程id,StationStepNumber+1
                    // 获取当前工站ID
                    int currentStationId = singleBatchEntryBLL.GetStationIdByProductId(productId);
                    // 通过id查询工站信息
                    Station stationdata = singleBatchEntryBLL.GetStationById(currentStationId);
                    // 获取总流程id
                    int totolId = stationdata.TotalProcessId;
                    // 获取当前步骤
                    int setup = stationdata.StationStepNumber;
                    // 获取总流程id获取所有工站
                    List<Station> stationTotolData = singleBatchEntryBLL.GetStationByTotolId(totolId);

                    // 检查是否是最后一步
                    if (setup < stationTotolData.Count)
                    {
                        // 获取下一个工站的 ID
                        int nextStationId = singleBatchEntryBLL.GetNextStationIdByTotalProcessIdAndStepNumber(totolId, setup);
                        // 获取产品数据
                        Product productData = singleBatchEntryBLL.GetProductById(productId);
                        productData.StationId = nextStationId;
                        // 通过工站id查询工艺流程id
                        int flowID = singleBatchEntryBLL.GetFlowIdByStationId(nextStationId);
                        productData.FlowId = flowID;
                        int Result = singleBatchEntryBLL.UpdateProduct(productData);
                    }
                    else if (setup == stationTotolData.Count)
                    {
                        // 当步骤等于总工站数时，将 flowId 和 stationId 设置为步骤数加 1
                        Product productData = singleBatchEntryBLL.GetProductById(productId);
                        productData.StationId = setup + 1;
                        productData.FlowId = setup + 1;
                        MessageBox.Show($"已是最后一步，该产品已完成所以流程");
                        int Result = singleBatchEntryBLL.UpdateProduct(productData);
                        if (Result <= 0)
                        {
                            MessageBox.Show("产品工站信息更新失败！");
                            return;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("产品进出站状态更新失败！");
                    return; // 如果状态更新失败，直接返回，不继续后续操作
                }

                // 获取备注
                string remarks = remark.Text.Trim();

                // 获取用户名
                string userNameText = userName.Text.Trim();
                if (string.IsNullOrEmpty(userNameText))
                {
                    MessageBox.Show("请输入用户名");
                    return;
                }

                // 根据用户名获取用户ID
                int userId = singleBatchEntryBLL.GetUserIdByUsername(userNameText);
                if (userId == -1)
                {
                    MessageBox.Show("未找到用户ID");
                    return;
                }
                // 创建 BatchStation 对象
                BatchStation batchStation = new BatchStation
                {
                    ProductId = productId,
                    //ProcessPackageId = processPackageId,
                    UserId = userId,
                    Remark = remarks,
                };
                BatchStationRepository batchStationRepository = new BatchStationRepository();
                // 调用 DAL 层的方法添加数据
                int result = batchStationRepository.AddBatchStation(batchStation);

                if (result > 0)
                {
                    MessageBox.Show("数据添加成功！");
                }
                else
                {
                    MessageBox.Show("数据添加失败！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}");
            }
        }
    }
}
